package org.dromara.system.task;

import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.config.properties.ThreadPoolProperties;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.RejectedExecutionException;

/**
 * 天眼查线程池
 */
@Slf4j
@AutoConfiguration
@EnableConfigurationProperties(ThreadPoolProperties.class)
public class SkyThreadConfig {

    /**
     * 天眼查线程管理
     * @return ThreadPoolTaskExecutor
     */
    @Bean(name = "skyThreadConfig")
    public ThreadPoolTaskExecutor skyExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
            // 核心线程数
            executor.setCorePoolSize(5);
            // 最大线程数
            executor.setMaxPoolSize(10);
            // 队列容量
            executor.setQueueCapacity(20);
            // 线程池维护线程所允许的空闲时间
            executor.setKeepAliveSeconds(60);
            // 线程名称前缀
            executor.setThreadNamePrefix("myExecutor-");
            // 等待所有任务结束后再关闭线程池
            executor.setWaitForTasksToCompleteOnShutdown(true);
            // 设置线程池拒绝策略
            executor.setRejectedExecutionHandler((r, executor1) -> {
                throw new RejectedExecutionException("SkyThreadConfig " + r.toString() + " rejected from " + executor1.toString());
            });
            // 初始化
            executor.initialize();
        return executor;
    }
}
